import { defineEventHandler, getQuery, createError } from 'h3'
import { FileModel } from 'server/models/File'
import { fileUploadService } from 'server/utils/fileUpload'

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event)
    const {
      category,
      page = '1',
      limit = '20',
      storageType
    } = query

    let files: any[] = []
    let total = 0

    // 根据查询条件获取文件列表
    if (category) {
      files = await FileModel.findByCategory(category as string, parseInt(limit as string), (parseInt(page as string) - 1) * parseInt(limit as string))
      // 获取分类文件总数
      const countQuery = `SELECT COUNT(*) as total FROM files WHERE category = ? AND status = 'active'`
      const countResult = await FileModel.query<any[]>(countQuery, [category])
      total = countResult[0]?.[0]?.total || 0
    } else if (storageType) {
      files = await FileModel.findByStorageType(storageType as any, parseInt(limit as string), (parseInt(page as string) - 1) * parseInt(limit as string))
      // 获取存储类型文件总数
      const countQuery = `SELECT COUNT(*) as total FROM files WHERE storage_type = ? AND status = 'active'`
      const countResult = await FileModel.query<any[]>(countQuery, [storageType])
      total = countResult[0]?.[0]?.total || 0
    } else {
      files = await FileModel.findAll(parseInt(limit as string), (parseInt(page as string) - 1) * parseInt(limit as string))
      // 获取文件总数
      const countQuery = `SELECT COUNT(*) as total FROM files WHERE status = 'active'`
      const countResult = await FileModel.query<any[]>(countQuery)
      total = countResult[0]?.[0]?.total || 0
    }

    // 为每个文件生成完整路径
    const filesWithFullPath = await Promise.all(
      files.map(async (file) => {
        const fullPath = await fileUploadService.generateFileUrl(file)
        return {
          ...file,
          full_path: fullPath
        }
      })
    )

    return {
      success: true,
      data: {
        files: filesWithFullPath,
        pagination: {
          page: parseInt(page as string),
          limit: parseInt(limit as string),
          total,
          pages: Math.ceil(total / parseInt(limit as string))
        }
      }
    }

  } catch (error: any) {
    console.error('获取文件列表错误:', error)
    
    if (error.statusCode) {
      throw error
    }

    throw createError({
      statusCode: 500,
      statusMessage: error.message || '服务器内部错误'
    })
  }
})